import requests
from .tracker import CVETracker
import time

def make_body(result: dict, tracker: CVETracker) -> str:
    """
        将result转化为str
    """
    new_result = {}
    for key, value in result.items():
        db = tracker.cve_data_db
        parent = None
        if db.check_os_version_is_openeuler(key):
            parent = db.get_os_parents(db.get_os_parents(key))
        else:
            parent = db.get_os_parents(key)
        full_key = f"{key} ({parent})"
        new_result[full_key] = result[key]
    return '\n'.join(f"{key}: {value}" for key, value in new_result.items())

def create_comment(parameter: dict, body: str):
    """
        在指定ISSUE下创建评论
        body: 评论内容
    """
    print("创建评论, 参数: ", parameter)
    access_token = parameter["access_token"]
    full_name = parameter["full_name"]
    number = parameter["number"]
    # 构造 API 地址
    url = f"https://gitee.com/api/v5/repos/{full_name}/issues/{number}/comments"
    
    # 请求头
    headers = {
        "Content-Type": "application/json;charset=UTF-8"
    }
    
    # 请求参数（包含认证信息）
    payload = {
        "access_token": access_token,  # Gitee 的认证方式
        "body": body
    }
    
    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()  # 检查 HTTP 错误

        print("评论创建成功！响应数据：")
        print(response.json())
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"请求失败：{str(e)}")
        if response:
            print(f"错误响应内容：{response.text}")
        return None

def create_pr(parameter: dict):
    """
        创建pr
    """
    access_token = parameter["access_token"]
    full_name = parameter["full_name"]
    title = parameter["title"]
    head = parameter["head"]
    base = parameter["base"]
    body = parameter["body"]
    # 构造 API 地址
    url = f"https://gitee.com/api/v5/repos/{full_name}/pulls"
    
    # 请求头
    headers = {
        "Content-Type": "application/json;charset=UTF-8"
    }
    
    # 请求参数（包含认证信息）
    payload = {
        "access_token": access_token,
        "title": title,
        "head": head,
        "base": base,
        "prune_source_branch": "true",
        "body": body
    }

    print("head type: ", type(head))
    print("head: ", head)

    print("创建pr:\njson: ", payload)
    print("headers: ", headers)
    print("url: ", url)

    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()  # 检查 HTTP 错误
        
        print("pr创建成功！响应数据：")
        print(response.json())
        return response
    except requests.exceptions.RequestException as e:
        print(f"Response Code: {response.status_code}")
        print("Response Headers:", response.headers)
        print("Response Body:", response.json())
        if (response.status_code == 400):
            print("Error Message: ", response.json()["message"])
        return response